import asyncio
import datetime
import logging
from os import makedirs
from os.path import exists

from pyppeteer import launch
from pyquery import PyQuery as pq

RESULTS_DIR='results'
exists(RESULTS_DIR) or makedirs(RESULTS_DIR)
WINDOW_WIDTH, WINDOW_HEIGHT=1920, 1080
HEADLESS=False

url='https://cloud.tencent.com/act/new'
timeout=100


async def init(url, timeout):
    global browser, page
    browser=await launch(headless=HEADLESS, ignoreHTTPSErrors=True,
                         args=['--disable-infobars',
                               f'--window-size={WINDOW_WIDTH},{WINDOW_HEIGHT}'])
    page=await browser.newPage()
    await page.setViewport({'width': WINDOW_WIDTH, 'height': WINDOW_HEIGHT})
    await page.goto(url, options={'timeout': int(timeout*1000)})
    # 防止检测(即隐藏WebDriver模仿成普通浏览器请求)
    await page.evaluateOnNewDocument('Object.defineProperty(navigator, "webdriver", {get: () => undefined})')


# 1.模拟点击各个页面
async def click_tame_tab():
    await page.waitForSelector('.uno-timeline-item-tit')
    doc=pq(await page.content())
    table_list=[item for item in doc(
        '.uno-timeline-card:nth-child(1) .uno-timeline-card-inner .uno-timeline-list li').items()]  # 获取商品名称
    # print(table_list)
    for i in range(1, len(table_list)+1):
        await page.click('.uno-timeline-list li:nth-child({})'.format(i), options={
            'button': 'left',
            'clickCount': 1,  # 1or2
            'delay': 3000  # 毫秒
        })
        try:
            await scrape_page()
        except:
            logging.info('失败，清检查原因')


# 2.提取页面数据
async def scrape_page():
    await page.waitForSelector('.uno-seckill-card')  # Page 对象调用 waitForSelector 方法，传入选择器，如果加载出来了，立即返回，否则会持续等待直到超时
    doc=pq(await page.content())

    for item in doc('.uno-seckill-card').items():
        productName=item('.uno-seckill-card-sub-tit-text').text()  # 名称
        productPeizhi=item('.uno-seckill-card-tit-text').text()  # 配置
        productDiqu=item('.uno-seckill-card-detail span').text()  # 地区
        productJiage=item('.uno-seckill-card-price.uno-show-pc span:nth-child(1)').text()+item(
            '.uno-seckill-card-price.uno-show-pc span:nth-child(2)').text()  # 价格

        print(productName, productPeizhi, productDiqu, productJiage)


async def main():
    await init(url, timeout)
    while True:
        await click_tame_tab()
        break
    await page.waitFor(1000)
    await browser.close()


if __name__=='__main__':
    starttime=datetime.datetime.now()
    asyncio.get_event_loop().run_until_complete(main())
    endtime=datetime.datetime.now()
    print("运行时间：{}s".format( (endtime-starttime).seconds))
